/*
* 合同 或者无后端合同申请中绑定业务机会
* 规则 : 选择 阶段为: 招标   有赢单率的业务机会进行关联 .关联之后将业务机会的阶段改为 合同签订
*/
public without sharing class BindOppoturnityController {
	public Id soId {get;set;}
	public Boolean isErr {get;set;}
	public Id accId ;
	public String seledOpp {get;set;}
	public List<SelectOption> oppOpts {get;set;}
	public Contract__c con ;
	public Boolean isSuccess {get;set;}
	public String msg  {get;set;}
    public BindOppoturnityController() {
        soId = System.currentPageReference().getParameters().get('id');
        oppOpts = new List<SelectOption>();
        getAccounId();
        getOppList();
    }
    public void getAccounId(){

    	If(soId != null){

    		
    			 con = [select Id,TerminalCustomer__c,Status__c  from Contract__c where Id=:soId];

    			if(con != null && con.TerminalCustomer__c != null ){
    				accId = con.TerminalCustomer__c;
             
                   
    			}else{
    				ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,'合同没有设置终端客户!'));

    				isErr = true;
    				return;
    			}
    			

	    }

    }
    public void getOppList(){

    	if(accId == null) return;
    	 List<Opportunity> oppList = [select Id,Name from Opportunity where AccountId =:accId and WinRatio__c != null  and StageName = '招标' ];
    	 if(oppList.size() == 0){
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,'没有满足条件的业务机会!'));

    	 	isErr = true;
    	 	return;
    	 }
    	  oppOpts.add( new SelectOption('','----请选择----'));

    	 for (Opportunity o : oppList) {
    	 	oppOpts.add( new SelectOption(o.Id,o.Name));
    	 }


    	
    }

    public void save(){
    		msg = '';
    		if(String.isBlank(seledOpp) == true){
    			msg = '请选择业务机会!';
    			return;
    		}
    		try {
    			con.Opportunity__c = seledOpp;
    			update con ;
	    		Opportunity opp = [select Id ,StageName from Opportunity where Id=:seledOpp];
	    		//opp.StageName = '合同签订';
	    		update opp;
	    		isSuccess = true;
	    		msg = '关联成功!';
    		}catch (Exception e) {
    		    msg = '关联失败!' +e.getMessage();

    		}
    		
    		
    }

}